package chat

import (
	"bufio"
	"encoding/json"
	"fmt"
	chatModel "gxcvu-ai/app/model/chat"
	"io"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type Openai struct {
	Model string `json:"model"`
}

type OpenaiRequest struct {
	Model          string    `json:"model"`
	Messages       []Message `json:"messages"`
	Stream         bool      `json:"stream"`
	ResponseFormat struct {
		Type string `json:"type"`
	} `json:"response_format"`
}

type OpenaiReponse struct {
	Id                string `json:"id"`
	Object            string `json:"object"`
	Created           int    `json:"created"`
	Model             string `json:"model"`
	SystemFingerprint string `json:"system_fingerprint"`
	Choices           []struct {
		Index int `json:"index"`
		Delta struct {
			Role    string `json:"role,omitempty"`
			Content string `json:"content"`
		} `json:"delta"`
		Logprobs     string `json:"logprobs"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
}

//https://api.openai.com/v1/chat/completions

func (e Openai) NewChat(data []chatModel.Message, c *gin.Context) {
	url := "https://api.openai.com/v1/chat/completions"
	const key = "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"

	payload := OpenaiRequest{
		Model:    e.Model,
		Messages: formatChatMessage(data),
		Stream:   true,
	}
	payload.ResponseFormat.Type = "text"

	postForm, _ := json.Marshal(payload)
	req, _ := http.NewRequest("POST", url, strings.NewReader(string(postForm)))
	req.Header.Add("Authorization", "Bearer "+key)
	req.Header.Add("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()
	// 转发 SSE 到客户端
	_, ok := c.Writer.(http.Flusher)
	if !ok {
		http.Error(c.Writer, "Streaming unsupported!", http.StatusInternalServerError)
		return
	}
	// 创建一个新的读取器和写入器，用于复制数据
	defer resp.Body.Close()
	reader := bufio.NewReader(resp.Body)
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}

		data := strings.TrimPrefix(string(line), "data:")
		var jsonData OpenaiReponse
		err = json.Unmarshal([]byte(data), &jsonData)
		if err != nil {
			fmt.Println("Error unmarshaling JSON:", err)
			continue
		}
		// 处理解析后的JSON数据...
		// fmt.Printf("Parsed JSON data: %+v\n", jsonData)
		chatResp := ChatResponse{
			IsEnd:   jsonData.Choices[0].FinishReason == "stop",
			Result:  jsonData.Choices[0].Delta.Content,
			Id:      jsonData.Id,
			Object:  "assistant",
			Created: jsonData.Created,
			Model:   jsonData.Model,
		}
		c.SSEvent("result", chatResp)
		c.Writer.Flush()
	}

}
